package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.exception.GlobalException;
import cn.itsource.hrm.service.ISmsVerifyCodeService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.SmsUtil;
import cn.itsource.hrm.util.StrUtils;
import org.apache.tomcat.util.bcel.classfile.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsVerifyCodeServiceImpl implements ISmsVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult verifySmsCode(Map<String,String> params) {
        String code = params.get("code");
        String key = params.get("key");
        String codeInRedis = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(codeInRedis))
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码不正确！");

        return code.equalsIgnoreCase(codeInRedis.split(":")[0])?AjaxResult.me()
                :AjaxResult.me().setSuccess(false).setMessage("短信验证码不正确！") ;
    }

    @Override
    public AjaxResult sendCode(Map<String, String> params) {
        String key = params.get("key");
        String codeNum = params.get("codeNum");
        String expire = params.get("expire");
        String phone = params.get("phone");
        String obj = (String) redisTemplate.opsForValue().get(key);
        String code = null;
        if(!StringUtils.isEmpty(obj)){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new GlobalException("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(Integer.valueOf(codeNum));
        }
        //设置值到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),Long.valueOf(expire), TimeUnit.MINUTES);
        //发送短信验证码
//        SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的验证码是：" + code + ",请在3分钟之内使用");
        return AjaxResult.me();
    }
}
